﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Meqs.Entity;
using Meqs.Entity.Views;
using Meqs.Logic;
using Meqs.Logic.Interface;
using Meqs.Utilities;

public partial class Credit_Teacher_DailyManage_Daily : ContainerBasePage
{
    /// <summary>
    /// 描述当前页面类型(0为当前学期数据  1为历史数据)
    /// </summary>
    private int pageType = 0;

    public int GetPageType {
        get { return string.IsNullOrEmpty(Request["type"]) ? 0 : Convert.ToInt32(Request["type"]); }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            // 获取页面类型 : 0为当前学期数据  1为历史数据
            if (!Int32.TryParse(Request["type"], out pageType))
                pageType = 0;

           // btnQuery_Click(btnQuery as object, new EventArgs());
        }
    }
 
    [WebMethod]
    public static List<string[]> YearChanged(int schoolYear, int term, int pageType)
    {
      //  BindMonth(nYear, nTerm);
        
        List<string[]> arr = new List<string[]>();
        if (pageType == 1)
        {// 当是历史界面时 获取学年学期数据 
 
            Hashtable ht = new Hashtable();
            ht.Add("SchoolMark", SchoolMark);
            ht.Add("SchoolYear", schoolYear);
            ht.Add("Term", term);
            IList<TermInfo> list = Container<ITermInfoLogic>.Instance.FindAll(ht);
            if (list == null || list.Count < 1)
            {
               // selSubject.Items.Add(new ListItem("-----", "-1"));
                arr.Add(new string[] { "-----", "-1" });
                return arr;
            }
            DateTime? dts = list[0].StartDate;
            
            if (term == 2)
            {
                schoolYear++;
                term = 1;
            }
            else
            {
                term = 2;
            }

            DateTime? dte = null;
            ht = new Hashtable();
            ht.Add("SchoolMark", SchoolMark);
            ht.Add("SchoolYear", schoolYear);
            ht.Add("Term", term);
            list = Container<ITermInfoLogic>.Instance.FindAll(ht);
            if (list == null || list.Count < 1)
                dte = DateTime.Now;
            else
                dte = list[0].StartDate;

           
            for (int i = 0; ; i++)
            {
                if (dts > dte && (dts.Value.Month > dte.Value.Month || dts.Value.Year > dte.Value.Year))
                    break;
               // selSubject.Items.Add(new ListItem(dts.Value.ToString("yyyy-MM"), dts.Value.Month.ToString()));
                arr.Add(new string[] { dts.Value.ToString("yyyy-MM"), dts.Value.Month.ToString() });
                dts = dts.Value.AddMonths(1);
            }
        }
        return arr;
    }
 

    /// <summary>
    /// 查询按钮事件
    /// </summary>
    protected void btnQuery_Click(object sender, EventArgs e)
    {
        int nYear = 0;
        int nTerm = 0;
        int nGrade = 0;
        int nSubject = 0;
        String date;
        string s = "";
        if (!Int32.TryParse(Request["type"], out pageType))
            pageType = 0;
        if (pageType == 1)
        {// 当是历史界面时 获取学年学期数据
            //string[] outString = selYear.SelectedValue.Split(new char[] { ',' });
            //if (outString.Length != 2)
            //    //throw new Exception("orz The param is worng");
            //    return;

            //if (!Int32.TryParse(outString[0], out nYear))
            //    //throw new Exception("orz The param is worng");
            //    return;

            //if (!Int32.TryParse(outString[1], out nTerm))
            //    //throw new Exception("orz The param is worng");
            //    return;
           
            s = txtYear.Text;
            if (!string.IsNullOrEmpty(s))
                int.TryParse(s, out nYear);

            s = txtTerm.Text;
            if (!string.IsNullOrEmpty(s))
                int.TryParse(s, out nTerm);
        }

        s = txtGrade.Text;
        if (!string.IsNullOrEmpty(s))
            int.TryParse(s, out nGrade);

        s = txtMonth.Text;
        if (!string.IsNullOrEmpty(s))
            int.TryParse(s, out nSubject);

        if(nSubject < 0)
            return;

        lblTitle.Text = Common.ConvertYearAndTerm(nYear, nTerm) + "&nbsp;&nbsp;"
                        + Common.ConvertGradeNum(nGrade) + "&nbsp;&nbsp;"
                        + nSubject+"月";


        date = txtMonthDate.Text;//selSubject.SelectedItem.Text;

        // 查找年级内班级
        Hashtable ht = new Hashtable();
        IList<VClsInfo> clsList = null;
        ht.Add("SchoolMark", SchoolMark);
        ht.Add("Grade", nGrade.ToString());
        //ht.Add("CauseID", nSubject.ToString());
        if (pageType != 1)
        {
            ht.Add("IsEffect", "1");
            clsList = Container<IClsInfoLogic>.Instance.FindClassInfoByCauseID(ht);
        }
        else
        {
            ht.Add("SchoolYear", nYear);
            clsList = Container<IClsInfoLogic>.Instance.FindClassInfoByCauseID(ht);
            //clsList = Container<IClassHistoryLogic>.Instance.FindClassesInSchoolYearToView(nYear, SchoolMark, nGrade);
        }
        if (clsList == null || clsList.Count < 1)
            return;

        IList<int> idList = new List<int>();
        foreach (VClsInfo info in clsList)
        {
            idList.Add(info.RID);
        }

        IList<GlobalCauseInfo> subjectList = Container<IGlobalCauseInfoLogic>.Instance.SelectSchoolCause(SchoolMark, 1);
        ht = new Hashtable();
        ht.Add("Grade", nGrade);
        ht.Add("SchoolMark", SchoolMark);
        IList<CouseGradeInfo> cgList = Container<ICouseGradeInfoLogic>.Instance.FindAll(ht);

        IList<GlobalCauseInfo> sl = new List<GlobalCauseInfo>();
        foreach (GlobalCauseInfo info in subjectList)
        {
            foreach (CouseGradeInfo gradeInfo in cgList)
            {
                if (gradeInfo.CourseID == info.RID)
                { 
                    sl.Add(info);
                    break;
                }
            }
        }

        IList<StuCauseEvalState> stateList = null;
        if (pageType == 1)
        {
            stateList =
                Container<IStuCauseEvalHistoryLogic>.Instance.GetStateWithDate(nYear, nTerm, SchoolMark, idList, date);
            ht = new Hashtable();
            ht.Add("SchoolMark", SchoolMark);
            ht.Add("SchoolYear", nYear);
            ht.Add("Term", nTerm);
            ht.Add("CauseID", nSubject);

            CreateTable(clsList, stateList, sl, nYear, nTerm, date);
        }
        else
        {
            stateList =
               Container<IStuCauseEvalHistoryLogic>.Instance.GetStateWithDate(SchoolCommon.Sch_SchoolInfo.SchoolYear,
                                                                   SchoolCommon.Sch_SchoolInfo.SchoolTerm,
                                                                   SchoolMark, idList, date);
            
            ht = new Hashtable();
            ht.Add("SchoolMark", SchoolMark);
            ht.Add("SchoolYear", SchoolCommon.Sch_SchoolInfo.SchoolYear);
            ht.Add("Term", SchoolCommon.Sch_SchoolInfo.SchoolTerm);
            ht.Add("CauseID", nSubject);

            CreateTable(clsList, stateList, sl,
                SchoolCommon.Sch_SchoolInfo.SchoolYear,
                SchoolCommon.Sch_SchoolInfo.SchoolTerm, date);
        }
    }

    /// <summary>
    /// 构造结果表格(历史)
    /// </summary>
    private void CreateTable(IList<VClsInfo> classInfo, IList<StuCauseEvalState> stateInfo, IList<GlobalCauseInfo> subjectList, 
                            int year, int term, String date)
    {
        List<int> gcList = SchoolCommon.CanViewSubjects((int)SecurityTable.Security.Credit_CanView, year, term);
        if (gcList != null)
        {
            IList<GlobalCauseInfo> gcList1 = Container<ITeachClsCauseLogic>.Instance.GetTeacherCourse(Common.GetUserInfo().UID, SchoolMark);

            foreach (GlobalCauseInfo h in gcList1)
            {

                gcList.Add(h.RID);
            }
        }
        List<int> enableSubjectList = SchoolCommon.CanViewClasses((int)SecurityTable.Security.Credit_CanView, year, term);

        IList<int> idList = new List<int>();
        foreach (VClsInfo info in classInfo)
        {
            idList.Add(info.RID);
        }
        IList<MoralityState> mstateList = Container<IMoralityHistoryLogic>.Instance.GetState(year, term, "", SchoolMark, idList);

        TableHeaderRow h1row = new TableHeaderRow();
        TableHeaderCell h1cell = new TableHeaderCell();
        h1cell.Text = lblTitle.Text;
        h1cell.ColumnSpan = subjectList.Count + 2;
        h1cell.CssClass = "FixedRowCol";
        h1row.Cells.Add(h1cell);
        tbResult.Rows.Add(h1row);

        int width = 90;
        TableHeaderRow hrow = new TableHeaderRow();
        TableHeaderCell hcell = new TableHeaderCell();
        hcell.Text = "班级";
        hcell.Style[HtmlTextWriterStyle.Width] = "90px";
        hcell.CssClass = "FixedRowCol";
        hrow.Cells.Add(hcell);

        // 构造表头
        foreach (GlobalCauseInfo info in subjectList)
        
        {
            if (gcList != null)
            {
                if (!gcList.Contains(info.RID))
                { continue; }
            }
            hcell = new TableHeaderCell();
            hcell.Text = info.CauseName;
            hcell.Style[HtmlTextWriterStyle.Width] = "75px";
            width += 75;
            hcell.CssClass = "FixedRow";
            hrow.Cells.Add(hcell);
        }
        hcell = new TableHeaderCell();
        hcell.Text = "学生德育";
        hcell.Style[HtmlTextWriterStyle.Width] = "75px";
        width += 75;
        hcell.CssClass = "FixedRow";
        hrow.Cells.Add(hcell);

        tbResult.Rows.Add(hrow);
        tbResult.Style[HtmlTextWriterStyle.Width] = String.Format("{0}px", width);
        tbResult.CssClass = "useList1";

        // 填充表内容
        TableRow row = null;
        TableCell cell = null;
        foreach (VClsInfo info in classInfo)
        {
            if (enableSubjectList != null)
            {
                if (!enableSubjectList.Contains(info.RID))
                {
                    continue;
                }
            }
            row = new TableRow();
            cell = new TableCell();
            cell.Text = info.ClsGradeName;
            cell.CssClass = "FixedCol";
            row.Cells.Add(cell);

            foreach (GlobalCauseInfo cause in subjectList)
            
            {
                if (gcList != null)
                {
                    if (!gcList.Contains(cause.RID))
                    { continue; }
                }
                cell = new TableCell();
                bool sign = false;
                foreach (StuCauseEvalState state in stateInfo)
                {
                    if (state.ClassID == info.RID && state.CauseID == cause.RID)
                    {
                        // 构造超链html标签
                        HyperLink control = new HyperLink();
                        control.Text = "已录入";
                        control.ToolTip = state.Daily.Year<2000 ? "" : state.Daily.ToString("yyyy-MM-dd hh:mm");
                        control.Attributes.Add("onclick", "detailView(1);");
                        control.NavigateUrl = String.Format("../ScoreInput/ScoreInput.aspx?SchoolYear={0}&Term={1}&ClsID={2}&Year={3}&Month={4}&CauseID={5}",
                                                year, term,
                                                state.ClassID, state.StartTime.Year, state.StartTime.Month, cause.RID);
                        cell.Controls.Add(control);
                        sign = true;
                        break;
                    }
                }
                if (!sign)
                {
                    IList<ClassTercher> classteachers = Container<ITeachClsCauseLogic>.Instance.FindClassTercherEx(info.RID, cause.RID);
                    if (classteachers.Count > 0)
                    {
                        cell.Text = classteachers[0].TeachName;
                    }
                    else
                    {
                        cell.Text = "未录入";
                    }
                    cell.Style[HtmlTextWriterStyle.Color] = "Red";
                }

                row.Cells.Add(cell);
            }
            bool sign1 = false;
            cell = new TableCell();
            foreach (MoralityState m in mstateList)
            {
                if (info.RID == m.ClassID
                    &&
                    date.Contains(m.StartTime.Year.ToString())
                    &&
                    date.Contains(m.StartTime.Month<10 ? "0"+m.StartTime.Month:m.StartTime.Month.ToString()))
                {
                    HyperLink control = new HyperLink();
                    control.Text = "已录入";
                    control.ToolTip = m.Daily.Year < 2000 ? "" : m.Daily.ToString("yyyy-MM-dd hh:mm");
                    //control.Attributes.Add("onclick", "detailView(1);");
                    control.NavigateUrl = String.Format("../../../Moral/Teacher/ScoreInput/ScoreInput.aspx?SchoolYear={0}&Term={1}&ClsID={2}&Year={3}&Month={4}",
                                                year, term,
                                                m.ClassID, m.StartTime.Year, m.StartTime.Month);
                    cell.Controls.Add(control);
                    sign1 = true;
                    break;
                }
            }
            row.Cells.Add(cell);
            if (!sign1)
            {

                cell.Text = info.Header;
                cell.Style[HtmlTextWriterStyle.Color] = "Red";
            }
            tbResult.Rows.Add(row);
        }
    }

    [WebMethod]
    public static string GetExcel(ExcelTableCell[][] cells)
    {
        for (int i = 0; i < cells.Length; i++)
        {
            for (int j = 0; j < cells[i].Length; j++)
            {
                if (i != 0 && i != 1 && j != 0 && !cells[i][j].Text.Equals("已录入"))
                {
                    cells[i][j].Color = "Red";
                }
            }
        }
        string temp_path = HttpContext.Current.Server.MapPath("../../../");
        string save_path = temp_path + "\\download\\" + String.Format("{0}_{1}_down.xls", Common.GetUserInfo().SchoolName, Common.GetUserInfo().UName);
        HttpContext.Current.Session["filepath"] = save_path;
        Meqs.Utilities.ExcelUtil.ExcelExport(save_path, "表格", 2, 0, cells);
        return "";
    }
}
